package com.tom.service.impl;

import com.tom.config.JwtProperties;
import com.tom.mapper.UserMapper;
import com.tom.model.User;
import com.tom.model.dto.UserInfo;
import com.tom.model.dto.UserInfoDto;
import com.tom.service.UserService;
import com.tom.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("UserService")
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties properties;

    @Override
    public List<User> findAll() {
        return this.userMapper.selectAll();
    }

    @Override
    public List<User> findAll2() {
        return this.userMapper.selectAll2();
    }

    @Override
    public User findById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public Long login(User user) {
        return userMapper.login(user);
    }

    @Override
    public UserInfoDto getUserInfo(Long id) {
        return userMapper.getUserInfo(id);
    }

    @Override
    public String authentication(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        Long uid = userMapper.login(user);
        if (uid == null){
            return null;
        }
        String token = null;
        try {
            token = JwtUtils.generateToken(new UserInfo(uid, username),
                    properties.getPrivateKey(), properties.getExpire());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }
}
